package persistent.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import basic.HibBaseDAO;
import basic.HibernateSessionFactory;
import model.TCloudAnecdote;
import model.TCloudAnecdoteReview;
import model.TCloudAnecdoteStudent;
import model.VCloudAnecdoteReview;
import persistent.dao.CloudAnecdoteDAO;
import util.toolkit.Constant;
import util.toolkit.LogUtil;
import util.toolkit.TimeUtil;

/**
 * 轶事业务接口实现类
 * @author 徐震霖
 *
 */
public class CloudAnecdoteImpl implements CloudAnecdoteDAO {

	private HibBaseDAO dao=null;
	Constant constant = new Constant();
	private static final Log log = LogFactory.getLog(HibBaseDAO.class);
	
	public CloudAnecdoteImpl() {
		dao = new HibBaseDAO();
	}
	
	/**
	 * 保存轶事（发送状态为：待发送）
	 * @param anecdote 轶事对象
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean saveAnecdote(TCloudAnecdote anecdote) {
		
		int row = dao.insert(anecdote);
		if (row > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 修改一条轶事信息
	 * @param anecdote 轶事类型对象
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean updateAnecdote(TCloudAnecdote anecdote) {
		TCloudAnecdote anecdote2=(TCloudAnecdote)dao.
				findById(TCloudAnecdote.class, anecdote.getAid());
		anecdote2.setTopic(anecdote.getTopic());
		anecdote2.setAcontent(anecdote.getAcontent());
		anecdote2.setInvolveStudent(anecdote.getInvolveStudent());
		anecdote2.setReceiveUserid(anecdote.getReceiveUserid());
		anecdote2.setSendUserid(anecdote.getSendUserid());
		anecdote2.setHandlerStatus(anecdote.getHandlerStatus());
		anecdote2.setSendStatus(anecdote.getSendStatus());
		anecdote2.setSendTime(anecdote.getSendTime());
		anecdote2.setAnecdotetype(anecdote.getAnecdotetype());
		anecdote2.setNumber(anecdote.getNumber());
		return dao.update(anecdote2);
	}

	/**
	 * 发送轶事（发送状态为：以发送）
	 * @param anecdote 轶事对象
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean sendAnecdote(TCloudAnecdote anecdote, Integer[] stuid) {

		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null; 
		tx = session.beginTransaction();
		
		try {
			//先发送一条轶事
			Serializable key = session.save(anecdote);
			//得到自动编号
			int row = ((Integer)key).intValue();
			if (row > 0) {
				for(int i = 0; i < stuid.length; i++){
					TCloudAnecdoteStudent astudent = new TCloudAnecdoteStudent();
					astudent.setAnecdoteid(row);
					astudent.setStuid(stuid[i]);
					//再保存轶事学生对应关系表
					session.save(astudent);
				}
				tx.commit();//统一提交
				session.close();//关闭连接
				return true;
			}
		} catch (Exception e) {
			if(tx != null) tx.rollback();
			session.close(); //关闭连接
			log.error("persistent.impl.CloudAnecdoteImpl类sendAnecdote(TCloudAnecdote anecdote, int[] stuid)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl.CloudAnecdoteImpl类sendAnecdote(TCloudAnecdote anecdote, int[] stuid)方法调用错误：");
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 发送已保存的轶事
	 * @param anecdoteid 轶事id
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean sendSaveAnecdote(int anecdoteid, Integer[] stuid) {
		
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null; 
		tx = session.beginTransaction();
		
		TCloudAnecdote anecdote;
		try {
			TimeUtil tUtil = new TimeUtil();
			anecdote = (TCloudAnecdote) 
					dao.findById(TCloudAnecdote.class, anecdoteid);
			anecdote.setSendStatus(Constant.ALREADY_SENT);
			anecdote.setSendTime(tUtil.toTimestamp(new Date()).toString());
			session.update(anecdote);
			for(int i = 0; i < stuid.length; i++){
				TCloudAnecdoteStudent astudent = new TCloudAnecdoteStudent();
				astudent.setAnecdoteid(anecdoteid);
				astudent.setStuid(stuid[i]);
				//再保存轶事学生对应关系表
				session.save(astudent);
			}
			tx.commit();//统一提交
			session.close();//关闭连接
			return true;
		} catch (Exception e) {
			if(tx != null) tx.rollback();
			session.close(); //关闭连接
			log.error("persistent.impl.CloudAnecdoteImpl类sendSaveAnecdote(int anecdoteid, int[] stuid)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl.CloudAnecdoteImpl类sendSaveAnecdote(int anecdoteid, int[] stuid)方法调用错误：");
			e.printStackTrace();
		}
		
		return false;
		
	}

	/**
	 * 删除一条轶事（只能删除未处理的轶事）
	 * @param anecdoteid 轶事id
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean deleteAnecdote(int anecdoteid) {
		
		TCloudAnecdote anecdote = (TCloudAnecdote) 
				dao.findById(TCloudAnecdote.class, anecdoteid);
		
		if (anecdote.getHandlerStatus() == constant.ALREADY_HANDLED) {
			return false;
		}
		else {
			if(dao.delete(anecdote)){
				return true;
			}
			else {
				return false;
			}
		}

	}

	/**
	 * 添加一条回复信息
	 * @param review 回复信息对象
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean addAnecdoteReview(TCloudAnecdoteReview review, TCloudAnecdote anecdote) {		
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null; 
		tx = session.beginTransaction();
		try {			
			//先保存发送信息
			Serializable key = session.save(review);
			//得到自动编号
			int row = ((Integer)key).intValue();
			if (row > 0) {
				session.update(anecdote);
			}
			tx.commit();//统一提交
			session.close();//关闭连接
			return true;
		} catch (Exception e) {
			if(tx != null) tx.rollback();
			session.close(); //关闭连接
			log.error("persistent.impl.CloudAnecdoteImpl类addAnecdoteReview(TCloudAnecdoteReview review, TCloudAnecdote anecdote)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl.CloudAnecdoteImpl类addAnecdoteReview(TCloudAnecdoteReview review, TCloudAnecdote anecdote)方法调用错误：");
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 通过轶事id得到一条轶事记录
	 * @param aid 轶事id
	 * @return 成功返回轶事TCloudAnecdote的对象，失败返回null
	 */
	@Override
	public TCloudAnecdote getTAndecdoteById(int aid) {
		return (TCloudAnecdote)dao.findById(TCloudAnecdote.class, aid);
	}
	
	/**
	 * 根据id得到一条轶事（包含回复）信息
	 * @param aid 轶事id
	 * @return 成功返回轶事VCloudAnecdoteReview的对象，失败返回null
	 */
	@Override
	public VCloudAnecdoteReview getAnecdoteByid(int aid) {
		return (VCloudAnecdoteReview) dao.findById(VCloudAnecdoteReview.class, aid);
	}

	/**
	 * 根据用户id得到该用户所有待发或已发轶事
	 * @param userid 用户id
	 * @param sendStutas 发送状态（1001-已发， 1002-待发）
	 * @param schoolid 学校id
	 * @return 成功返回List<VCloudAnecdoteReview>的对象列表，失败返回null
	 */
	@Override
	public List<VCloudAnecdoteReview> getAnecdotesByUseridSending(int userid,
			int sendStutas, String schoolid) {	
		String hql = "from VCloudAnecdoteReview where sendUserid = ? and sendStatus = ? and sendSchool = ? order by sendTime desc";
		Object[] para = {userid, sendStutas, schoolid};
		return dao.select(hql, para);
	}

	/**
	 * 根据用户id得到该用户所有待处理和已处理的轶事
	 * @param userid 用户id
	 * @param handlerStatus 处理状态（1001-已处理， 1002-未处理）
	 * @param schoolid 学校id
	 * @return 成功返回List<VCloudAnecdoteReview>的对象列表，失败返回null
	 */
	@Override
	public List<VCloudAnecdoteReview> getAnecdotesByUseridHandler(int userid,
			int handlerStatus, String schoolid) {		
		String hql = "from VCloudAnecdoteReview where receiveUserid = ? and handlerStatus = ? and sendSchool = ? order by sendTime desc";
		Object[] para = {userid, handlerStatus};
		return dao.select(hql, para);
	}

	/**
	 * 根据查询条件得到该用户所有待发或已发轶事
	 * @param strWhere 查询条件
	 * @return 成功返回List<VCloudAnecdoteReview>的对象列表，失败返回null
	 */
	@Override
	public List<VCloudAnecdoteReview> getAnecdotesByStrWhere(String strWhere) {
		String hql = "from VCloudAnecdoteReview " + strWhere;
		return dao.select(hql);
	}

	/**
	 * 根据查询条件得到一个带分页的事项
	 * @param strWhere 查询条件
	 * @param currentPage 当前页
	 * @param pageSize每页数
	 * @return 成功返回List<VCloudAnecdoteReview>的对象列表，失败返回null
	 */
	@Override
	public List<VCloudAnecdoteReview> getAnecdotesByStrWhere(String strWhere,
			int currentPage, int pageSize) {
		String hql="from VCloudAnecdoteReview "+strWhere;
		return dao.selectByPage(hql, currentPage, pageSize);
	}

	/**
	 * 得到摸个教师所带的班级（去除重复）
	 * @param strwhere 查询条件
	 * @return 成功返回VCloudTeacherUserClass列表，失败返回null
	 */
	/*@Override
	public List<VCloudTeacherUserClass> getTeacherUserClassByWhere(String strwhere) {
		String hql="from VCloudTeacherUserClass "+strwhere;
		return dao.select(hql);
	}*/

}
